using Microsoft.AspNetCore.Http;
using System.Security.Claims;

namespace B.S.Medical.Api.Write.Common
{
    public class IdentityService : IIdentityService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public IdentityService(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public string UserId => _httpContextAccessor.HttpContext?.User?.FindFirst("UserId")?.Value ?? string.Empty;
        public string UserName => _httpContextAccessor.HttpContext?.User?.FindFirst("UserName")?.Value ?? string.Empty;
        public string RealName => _httpContextAccessor.HttpContext?.User?.FindFirst("RealName")?.Value ?? string.Empty;
        
        /// <summary>
        /// 获取当前登录用户的显示名称（使用用户名）
        /// </summary>
        public string DisplayName => UserName;
        
        /// <summary>
        /// 检查用户是否已认证
        /// </summary>
        public bool IsAuthenticated => _httpContextAccessor.HttpContext?.User?.Identity?.IsAuthenticated ?? false;
        
        /// <summary>
        /// 获取所有用户声明信息（用于调试）
        /// </summary>
        public string GetAllClaims()
        {
            var user = _httpContextAccessor.HttpContext?.User;
            if (user == null) return "HttpContext.User is null";
            
            var claims = user.Claims.Select(c => $"{c.Type}: {c.Value}");
            return string.Join(", ", claims);
        }
    }

    public interface IIdentityService
    {
        string UserId { get; }
        string UserName { get; }
        string RealName { get; }
        /// <summary>
        /// 获取当前登录用户的显示名称（使用用户名）
        /// </summary>
        string DisplayName { get; }
        bool IsAuthenticated { get; }
        string GetAllClaims();
    }
} 